from django.contrib import messages
from django.db.models import Q
from django.shortcuts import render, redirect, reverse
from django.views import View
from django.contrib.auth import authenticate, login, logout

from apps.account.form import AccountLoginForm, AccountRegisterForm
from apps.account.models import Account


class LoginView(View):
    @property
    def get_redirect(self):
        return reverse("accounts:login")

    def get(self, request):
        form = AccountLoginForm()
        context = {
            "title": "登录",
            "form": form,
        }
        return render(request, 'account/login.html', context=context)

    def post(self, request):
        next = request.GET.get('next', '/')
        form = AccountLoginForm(data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect(next)
            else:
                messages.error(request, '用户名或密码错误')
        else:
            messages.error(request, '用户名或密码错误')
        return redirect(self.get_redirect + "?next=" + request.GET.get('next', '/'))


class LogoutView(View):
    def get(self, request):
        logout(request)
        next = request.GET.get('next', '/')
        return redirect(next)


class RegisterView(View):

    @property
    def get_redirect(self):
        return reverse("accounts:register")

    def get(self, request):
        form = AccountRegisterForm()
        context = {
            "title": "注册",
            "form": form,
        }
        return render(request, 'account/login.html', context=context)

    def post(self, request):
        form = AccountRegisterForm(data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            email = form.cleaned_data.get('email')
            account = Account.objects.filter(Q(username=username) | Q(email=email))
            if account.exists():
                messages.error(request, "该用户已存在")
            else:
                Account.objects.create_user(username=username, password=password, email=email)
                login_url = reverse("accounts:login") + "?next=" + request.GET.get('next', '/')
                return redirect(login_url)
        else:
            messages.error(request, '注册用户失败')
        return redirect(self.get_redirect)
